<template>
  <div class="page-container">
    <el-card class="content-container">
      <div class="toolbar">
        <div class="toolbar-left">
          <h3>评价管理</h3>
        </div>
        <div class="toolbar-right">
          <el-button type="danger" :disabled="selectedRows.length===0" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.yonghuName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.nongchanpinName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="评分">
          <el-select v-model="searchForm.nongchanpinCommentbackPingfenNumber" placeholder="请选择评分" clearable>
            <el-option label="1星" :value="1" />
            <el-option label="2星" :value="2" />
            <el-option label="3星" :value="3" />
            <el-option label="4星" :value="4" />
            <el-option label="5星" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="(rows)=>selectedRows=rows"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="yonghuName" label="评价用户" />
        <el-table-column prop="nongchanpinName" label="商品名称" />
        <el-table-column label="评分" width="120">
          <template #default="scope">
            <el-rate
              v-model="scope.row.nongchanpinCommentbackPingfenNumber"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
        <el-table-column prop="nongchanpinCommentbackText" label="评价内容" min-width="200">
          <template #default="scope">
            <div class="comment-text">
              {{ scope.row.nongchanpinCommentbackText }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="replyText" label="商家回复" min-width="200">
          <template #default="scope">
            <div class="reply-text">
              {{ scope.row.replyText || '暂无回复' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="评价时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleView(scope.row)">
              查看详情
            </el-button>
            <el-button type="primary" size="small" @click="handleReply(scope.row)">
              回复
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 评价详情对话框 -->
      <el-dialog v-model="detailDialog.visible" title="评价详情" width="600px">
        <div v-if="commentDetail" class="comment-detail">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-section">
                <h4>基本信息</h4>
                <p><strong>用户名：</strong>{{ commentDetail.yonghuName }}</p>
                <p><strong>商品名称：</strong>{{ commentDetail.nongchanpinName }}</p>
                <p><strong>评价时间：</strong>{{ commentDetail.insertTime }}</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-section">
                <h4>评分</h4>
                <el-rate
                  v-model="commentDetail.nongchanpinCommentbackPingfenNumber"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value} 分"
                />
              </div>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px;">
            <el-col :span="24">
              <div class="detail-section">
                <h4>评价内容</h4>
                <p class="comment-content">{{ commentDetail.nongchanpinCommentbackText }}</p>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="commentDetail.replyText" style="margin-top: 20px;">
            <el-col :span="24">
              <div class="detail-section">
                <h4>商家回复</h4>
                <p class="reply-content">{{ commentDetail.replyText }}</p>
              </div>
            </el-col>
          </el-row>
        </div>
        <template #footer>
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const instance = getCurrentInstance()
const http = instance?.proxy?.$http

// 响应式数据
const loading = ref(false)
const tableData = ref([])
let selectedRows = ref([])

// 评价详情对话框
const detailDialog = reactive({ visible: false })
const commentDetail = ref(null)

const searchForm = reactive({
  yonghuName: '',
  nongchanpinName: '',
  nongchanpinCommentbackPingfenNumber: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 模拟数据
const mockData = [
  {
    id: 1,
    yonghuName: '张三',
    nongchanpinName: '有机西红柿',
    nongchanpinCommentbackPingfenNumber: 5,
    nongchanpinCommentbackText: '商品质量很好，新鲜度不错，包装也很仔细，下次还会购买！',
    replyText: '感谢您的好评，我们会继续努力提供优质的农产品！',
    createTime: '2024-08-16 10:30:00'
  },
  {
    id: 2,
    yonghuName: '李四',
    nongchanpinName: '新鲜苹果',
    nongchanpinCommentbackPingfenNumber: 4,
    nongchanpinCommentbackText: '苹果很甜，口感不错，就是有点小贵。',
    replyText: '',
    createTime: '2024-08-15 09:20:00'
  }
]

// 方法
const loadData = async () => {
  if (!http) {
    ElMessage.error('系统初始化失败，请刷新页面重试')
    return
  }
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.size,
      ...searchForm
    }

    const res = await http({
      url: '/nongchanpinCommentback/page',
      method: 'get',
      params
    })

    if (res.code === 0) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载评价数据失败')
    }
  } catch (e) {
    console.error('加载评价数据失败', e)
    ElMessage.error('加载评价数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleView = async (row) => {
  try {
    const res = await http({
      url: `/nongchanpinCommentback/info/${row.id}`,
      method: 'get'
    })
    if (res.code === 0) {
      commentDetail.value = res.data
      detailDialog.visible = true
    } else {
      ElMessage.error(res.msg || '获取评价详情失败')
    }
  } catch (e) {
    console.error('获取评价详情失败', e)
    ElMessage.error('获取评价详情失败')
  }
}

const handleBatchDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条评价记录吗？`,
      '批量删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const ids = selectedRows.value.map(r => r.id)
    const res = await http({ url: '/nongchanpinCommentback/delete', method: 'post', data: { ids } })
    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('批量删除失败', e)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleReply = (row) => {
  ElMessage.info(`回复评价: ${row.nongchanpinCommentbackText}`)
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户"${row.yonghuName}"的评价吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadData()
  })
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/index.scss';

.comment-text,
.reply-text {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.reply-text {
  color: #666;
  font-style: italic;
}

.comment-detail {
  .detail-section {
    margin-bottom: 20px;

    h4 {
      margin-bottom: 10px;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 5px;
    }

    p {
      margin: 8px 0;
      line-height: 1.6;
    }

    .comment-content, .reply-content {
      background: #f5f7fa;
      padding: 15px;
      border-radius: 4px;
      line-height: 1.8;
      word-break: break-all;
    }

    .reply-content {
      background: #e8f4fd;
    }
  }
}
</style>
